package org.example.judge_contest.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.util.MyUtils;
import org.example.judge_contest.request.RequestContestAnnounceParams;
import org.example.judge_contest.request.RequestRegisterParams;
import org.example.judge_contest.service.ContestRecordService;
import org.example.judge_contest.service.ContestRegisterService;
import org.example.judge_contest.service.ContestService;
import org.example.judge_feign_api.UserClient;
import org.example.judge_pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/contest/register")
@CrossOrigin
public class ContestRegisterController {
    @Qualifier("ContestRecordServiceImpl")
    @Autowired
    private ContestRecordService contestRecordService;
    @Qualifier("ContestRegisterServiceImpl")
    @Autowired
    private ContestRegisterService contestRegisterService;

    @Qualifier("ContestServiceImpl")
    @Autowired
    private ContestService contestService;

    @Autowired
    private UserClient userClient;
    /**
     * 获取用户的报名信息
     * @param contestId
     * @param request
     * @return
     */
    @PostMapping("/select/{id}")
//    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult select(@PathVariable("id") String contestId,HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        if(loginUser==null)return ResponseResult.success();
        ContestRegister res = contestRegisterService.getByUserIdAndContestId(loginUser.getId(), contestId);

        if(res!=null&&res.getStatus()==1)return ResponseResult.info("用户已被拉黑");
        return ResponseResult.success().setData(res);
    }

    @PostMapping("/search")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult search(RequestRegisterParams params, HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        //非管理员只能看自己的
        if(!Auth.isAdmin(loginUser))params.setUserId(loginUser.getId());
        PageResult<ContestRegister> res = contestRegisterService.search(params);
        if(MyUtils.isNotEmpty(params.getUserId())){  //查询比赛题目信息
            //查不查嘞
            for (ContestRegister register : res.getDataList()) {
                register.setContest(contestService.getById(register.getContestId()));
                if(register.getContest()==null)continue;
                if(register.getContest().getStatus()!=0){ //比赛已开始，获取通过率
                    Integer count = contestRecordService.acceptProblemCount(loginUser.getId(), register.getContestId());
                    register.setUserId(count.toString());  //使用userID临时存储通过数量


                }else{
                    register.setUserId("未开始");  //使用userID临时存储通过数量
                }
            }
        }

        return ResponseResult.success().setData(res);
    }


    @PostMapping("/save")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult save(@RequestBody ContestRegister register, HttpServletRequest request){

        Contest contest = contestService.getById(register.getContestId());
        if(contest==null)return ResponseResult.fail("不存在的比赛");
        if(contest.getRegisterBeginTime().getTime()>System.currentTimeMillis())return ResponseResult.fail("报名还未开始");
        if(contest.getRegisterEndTime().getTime()<System.currentTimeMillis())return ResponseResult.fail("报名已截止");
        if (contest.getAuth()==1) {  //需要比赛密码
            if (!register.getPassword().equals(contest.getPassword())) {
                return ResponseResult.fail("比赛邀请码不正确");
            }
        }
        User loginUser = (User) request.getAttribute("loginUser");
        ContestRegister one = contestRegisterService.getByUserIdAndContestId(loginUser.getId(), register.getContestId());

        if(one!=null) {
            if(one.getStatus()==1)return ResponseResult.fail("用户已被拉黑");
            return ResponseResult.fail("已报名");
        }
        register.setUserId(loginUser.getId());
        register.setUsername(loginUser.getUsername());
        register.setSchoolName(loginUser.getSchool());

        contestRegisterService.save(register);

        return ResponseResult.success();
    }
    @PutMapping("/update")
    @AuthAnnotation({Auth.ADMINISTRATOR})
    public ResponseResult update(@RequestBody ContestRegister register, HttpServletRequest request){
        contestRegisterService.updateById(register);
        return ResponseResult.success();
    }

    /**
     * 更新用户信息--》username school
     * @param userId
     * @param request
     * @return
     */
    @PutMapping("/updateUser")
    public ResponseResult updateUser(@RequestParam String userId, HttpServletRequest request){
        if(MyUtils.isEmpty(userId))return ResponseResult.NotData();
        Object data = userClient.getUser(userId).getData();

//        System.out.println(data);
        if(data==null)return ResponseResult.NotData();
        Map user = (LinkedHashMap) data;
        contestRegisterService.update(new UpdateWrapper<ContestRegister>().set("username",user.get("username")).set("school_name",user.get("school")).eq("user_id",userId));
        return ResponseResult.success();
    }

    @DeleteMapping("/cancel/{id}")
    @AuthAnnotation({Auth.CLIENT})
    public ResponseResult delete(@PathVariable("id")String contestId,String userId,HttpServletRequest request){
        Contest byId = contestService.getById(contestId);
        if(byId==null)return ResponseResult.fail("不存在的比赛");
        if(byId.getStatus()==2)return ResponseResult.fail("比赛已结束");

        User loginUser = (User) request.getAttribute("loginUser");
        if(Auth.isAdmin(loginUser)&&MyUtils.isNotEmpty(userId)){
            loginUser.setId(userId);
        }
        contestRegisterService.delete(contestId,loginUser.getId());
        return ResponseResult.success();
    }
}

